<template>
  <el-dialog
    :title="RolesruleForm.roleId ? '编辑角色' : '添加角色'"
    :visible="addRolesDialog"
    width="50%"
    @close="addClose"
  >
    <el-form
      :model="RolesruleForm"
      :rules="Rolesrules"
      ref="addrolesRef"
      label-width="100px"
    >
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="RolesruleForm.roleName"></el-input>
      </el-form-item>
      <el-form-item label="角色描述" prop="roleDesc">
        <el-input v-model="RolesruleForm.roleDesc"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="addClose">取 消</el-button>
      <el-button type="primary" @click="ifRolesAgree()">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { addRights, idRights, editRights } from '@/api/roles'
export default {
  props: {
    RolesruleForm: {
      type: Object,
      default() {
        return {
          RolesruleForm: {
            roleId: '', // 角色 ID 必填
            roleName: '', // 角色名称 不能为空
            roleDesc: '' // 角色描述
          }
        }
      }
    },
    addRolesDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      Rolesrules: {
        roleName: [
          {
            required: true,
            message: '请填写角色名称',
            trigger: 'blur'
          }
        ],
        roleDesc: [{ message: '请填写角色描述', trigger: 'blur' }]
      }
    }
  },
  methods: {
    // 重置添加
    addClose() {
      this.$emit('update:addRolesDialog', false)
      this.$refs.addrolesRef.resetFields()
      // this.editRolesDialog = false
    },
    //  判断
    async ifRolesAgree() {
      if (this.RolesruleForm.roleId) {
        await this.editAgree()
        // 编辑
      } else {
        await this.rolesAgree()
        // 修改
      }
      this.$parent.loadUserList()
      this.addClose()
    },
    // 点击确定编辑角色
    async editAgree() {
      const res = await editRights(this.RolesruleForm)
      if (res.meta.status === 200) {
        this.$message.success('编辑角色成功')
      } else {
        this.$message.error('编辑角色失败')
      }
    },
    // 添加角色
    async rolesAgree() {
      const res = await addRights(this.RolesruleForm)
      if (res.meta.status === 201) {
        this.$message.success(res.meta.msg)
      } else {
        this.$message.error(res.meta.msg)
      }
    },
    // 根据id查询角色
    async rolesEditid(id) {
      this.editRolesDialog = true
      const res = await idRights(id)
      if (res.meta.status === 200) {
        // 把数据传入到编辑表单里
        this.editRolesruleForm = res.data
      } else {
        this.$message.error('获得角色数据失败')
      }
    }
  }
}
</script>

<style lang="less" scoped></style>
